import {message} from 'antd';
import axios, {AxiosError, AxiosRequestConfig} from "axios";
import qs from 'qs';

export const request: GeminisRequest = (url, opts) => {
  opts.loadingSetter?.(true);
  return axios.request({
    url: url,
    data: opts.method?.toLowerCase() === 'get' ? null : opts.requestData,
    params: opts.method?.toLowerCase() === 'get' ? opts.requestData : null,
    paramsSerializer: (params) => {
      return qs.stringify(params, {indices: false});
    },
    ...opts
  }).then((response) => {
    opts.loadingSetter?.(false);
    return opts.getResponse ? response : response.data;
  }).catch((error: AxiosError) => {
    opts.loadingSetter?.(false);
    if (opts.errMsg) {
      message.error(opts.errMsg);
    }
    return Promise.reject(error);
  })
};

export interface GeminisRequestOptions extends AxiosRequestConfig {
  loadingSetter?: React.Dispatch<boolean>;
  requestData?: any;
  errMsg?: string;
  getResponse?: boolean;
}

export interface GeminisRequest {
  <T = any>(url: string, opts: GeminisRequestOptions): Promise<T>;

  <T = any>(url: string): Promise<T>
}
